package com.tl.commonlibrary.ui.web;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;

import com.tl.commonlibrary.R;
import com.tl.commonlibrary.event.LoginStatusEvent;
import com.tl.commonlibrary.ui.BaseFragment;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * 承载WebView的展示，没有顶部导航栏，需要导航栏请使用{@link WebActivity}
 * 局部展示WebView时可使用WebFragment
 * Created by JongSung on 17/2/17.
 */

public class WebFragment extends BaseFragment {
    public static final String KEY_WEB_URL = "url";//链接地址
    public static final String KEY_WEB_CAN_GO_BACK = "can_go_back";//按下物理返回键是否允许返回上一级
    public static final String KEY_WEB_JS_NAME = "javascript_name";//JavaScript别名
    private WebFragmentModel model;
    private WebFragmentViewModel viewModel;

    public static WebFragment newInstance(String url) {
        return newInstance(url, true);
    }

    public static WebFragment newInstance(String url, boolean canGoBack) {
        return newInstance(url, canGoBack, null);
    }

    public static WebFragment newInstance(String url, String javaScriptName) {
        return newInstance(url, false, javaScriptName);
    }

    /**
     * @param url            链接地址
     * @param canGoBack      是否允许WebView返回上一级界面
     * @param javaScriptName JavaScript对象的别名，默认为{@link WebFragmentModel#sDefaultJavaScriptName},通过{@link WebFragmentModel#setJavascriptName(String)}设置
     * @return
     */
    public static WebFragment newInstance(String url, boolean canGoBack, String javaScriptName) {
        Bundle args = new Bundle();
        args.putString(KEY_WEB_URL, url);
        args.putBoolean(KEY_WEB_CAN_GO_BACK, canGoBack);
        if (!TextUtils.isEmpty(javaScriptName)) {
            args.putString(KEY_WEB_JS_NAME, javaScriptName);
        }
        WebFragment fragment = new WebFragment();
        fragment.setArguments(args);
        return fragment;
    }

    public WebFragment() {
        viewModel = new WebFragmentViewModel(this);
        model = new WebFragmentModel();
    }

    public WebFragmentModel getModel() {
        return model;
    }

    public WebFragmentViewModel getViewModel() {
        return viewModel;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        root = inflater.inflate(R.layout.web_layout, container, false);
//        initLoadingView(binding.pvLoadingContainer.getRoot());
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        model.init();
        viewModel.setModel(model);
        viewModel.init();
        if (getArguments() != null) {
            model.setOriginalUrl(getArguments().getString(KEY_WEB_URL));//url
            model.setJavascriptName(getArguments().getString(KEY_WEB_JS_NAME));
            setCanBoBack(getArguments().getBoolean(KEY_WEB_CAN_GO_BACK));//是否可以返回上一级
        }
        if (!WebActivity.LOAD_HTML.equals(getOriginalUrl())) {
            viewModel.loadUrl();
        }
        return root;
    }

    public void setWebListener(WebListener webListener) {
        if (viewModel != null) {
            viewModel.setWebListener(webListener);
        }
    }

    public boolean canGoBack() {
        if (model != null && model.isCanGoBack() && viewModel != null && viewModel.webView.canGoBack()) {
            return true;
        }
        return false;
    }

    public boolean goBack() {
        boolean canGoBack = canGoBack();
        if (canGoBack && viewModel != null) {
            viewModel.webView.goBack();
        }
        return canGoBack;
    }

    public void setCanBoBack(boolean canGoBack) {
        if (model != null) {
            model.setCanGoBack(canGoBack);
            if (viewModel != null) {
                if (canGoBack) {
                    viewModel.webView.setOnKeyListener(viewModel);
                } else {
                    viewModel.webView.setOnKeyListener(null);
                }
            }
        }
    }

    public String getUrl() {
        if (model != null) {
            return model.getUrl();
        }
        return null;
    }

    public String getOriginalUrl() {
        if (model != null) {
            return model.getOriginalUrl();
        }
        return null;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(LoginStatusEvent event) {
        if (viewModel != null) {
            viewModel.loadUrl();
        }
    }

    public void setUrl(String url) {
        WebFragmentModel model = getModel();
        if (model != null) {
            model.setOriginalUrl(url);
        }
    }

    public void loadUrl(String url) {
        setUrl(url);
        loadUrl();
    }

    public void loadUrl() {
        WebFragmentViewModel viewModel = getViewModel();
        if (viewModel != null) {
            viewModel.loadUrl();
        }
    }

    public void loadHtml(String data) {
        WebFragmentViewModel viewModel = getViewModel();
        if (viewModel != null) {
            viewModel.loadHtml(data);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (viewModel != null && viewModel.getRoot() != null) {
            ((ViewGroup) viewModel.getRoot()).removeView(viewModel.webView);
            viewModel.webView.destroy();
        }
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    public WebView getWebView() {
        if (viewModel != null) {
            return viewModel.getWebView();
        }
        return null;
    }

    @Override
    public void onClick(View v) {

    }
}
